var express = require('express');
var router = express.Router();
//const base = require('../public/js/sql.js');//引用连接mysql的js文件
var bodyParser = require("body-parser");
//const session = require('express-session');
var svgCaptcha = require('svg-captcha');
//-------
const http = require("http");
const mysql = require("mysql");

const LandOverTime = 7 ;//单位天
/*
  host: "49.245.203.72",
        user: 'root',
        password: "xiaocaimi",
        database: "vuedemo"
*/

const dbBase = (sql, data, callback) => {
    //定义链接数据库的参数值
    const connection = mysql.createConnection({
		host: "43.143.149.54",
        user: 'vuedemo',
        password: "8X3dWBdtcW4e3L2a",
        database: "vuedemo"
    })
    connection.connect(() => {
		let timer = new Date();
        //console.log(`数据库连接成功 -- ${timer}`);
    })

    connection.query(sql,data, (err, result) => {
        if (err) return console.log(err.message);
        // console.log("查询结果:", result);
        callback(null, result);
    })
    connection.end();
}

const dbBasecBolg= (sql, data, callback) => {
    //定义链接数据库的参数值
    const connection = mysql.createConnection({
        host: "43.143.149.54",
        user: 'vuedemo',
        password: "8X3dWBdtcW4e3L2a",
        database: "vuedemo"
    })
    connection.connect(() => {
		let timer = new Date();
        //console.log(`数据库连接成功 -- ${timer}`);
    })

    connection.query(sql,data, (err, result) => {
        if (err) return console.log(err.message);
        // console.log("查询结果:", result);
        callback(null, result);
    })
    connection.end();
}

function connectMysqlBolg(sql, data, callback) {
    dbBasecBolg(sql, data, (err, results) => {
        if (err) return res.status(500).send("Server Error...");
        callback(results);
    })
}

//-----ding yi fangfa
function connectMysql(sql, data, callback) {
    dbBase(sql, data, (err, results) => {
        if (err) return res.status(500).send("Server Error...");
        callback(results);
    })
}

function supeSelect(sql,query){
    var flog = false;
	//console.log(query,44);
	//console.log(query.err,45);
	//if(!query.err) return sql;
	//c
    for(var x in query){
		if(x!='page' && x!='pagesize'){
			var key = x;
			var val = query[x];
			var isarr = Array.isArray(val)
			var type = typeof(val);
			if(!flog){
				sql+=' where ';
			}else{
				sql+=' and ';
			}
			flog = true;
			if(!isarr){
				sql +=  ` \`${key}\` = '${val}' `
			}else{
				sql += ` \`${key}\` in (`
				for(var x=0;x<val.length;x++){

					if(x!=0){
						sql +=  ` , ` ;
					}
					sql += ` '${val[x]}' `;
				}
				sql += ` ) `
			}
		}
	}
        
    return sql;
}


function supeUpadte(tabName,keyObj,valObj){
	var sql=` update  ${tabName} set ` ;
	var kFlog = false;
	for(var x in keyObj){
			var key = x;
			var val = keyObj[x];
			if(kFlog){
				sql +=  ` , `;
			}
			kFlog = true;
			sql +=  ` \`${key}\` = '${val}' `
	}
	var vFlog = false;
	sql +=  ` where `
	for(var x in valObj){
			var key = x;
			var val = valObj[x];
			if(vFlog){
				sql +=  ` and `;
			}
			vFlog = true;
			sql +=  ` \`${key}\` = '${val}' `
	}
			return sql;
}
function supeInsert(sql, query) {
    var keySrc = '(';
    var valSrc = '(';
    var flog = true;
    for (var x in query) {
        var key = x;
        var val = query[x];
        if (flog) {
            keySrc += ` \`${key}\` `;
            valSrc += ` '${val}' `;
        } else {
            keySrc += `, \`${key}\` `;
            valSrc += `, '${val}' `;
        }
        flog = false;
    }
    keySrc += ')';
    valSrc += ')';
    return `${sql} ${keySrc} values ${valSrc}`;
}

function lostKeyStop(res,list,query){
    for(var key of list){
        if(query[key]==undefined){
            res.json(pushError(key+'为必须键'));
            res.end();
            return true;
        }
    }
    return false;
}

function pushOk(data){
    var obj = {};
    
    obj.code = 200;
    obj.msg = '请求成功';
    obj.data = data;
    return obj;
}

function pushError(msg){
    var obj = {};
    obj.code = 500;
    obj.msg = msg;
    obj.data = [];
    return obj;
}

function setPage(sql,start, len) {
	var page =start;
	var len = (len==undefined)?50:len;
    return (page==undefined)?sql:`${sql} limit ${(start-1)*len	},${len}`;
}
//小财迷首页
router.get('/', function (req, res, next) {
        res.render('index.html');
})
/*
router.get('/API', function (req, res, next) {
        res.render('inner.html');
})
*/
//京东轮播
router.get('/hellogirl', function (req, res, next) {
        res.json(pushOk("嗨！最近过的好吗"));
		res.end()
})



//京东轮播
router.get('/vuedemo/banner', function (req, res, next) {
	var queryData = req.query;
	var sql =  supeSelect("select * from homeBanner",queryData);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
		res.end()
    })
})
//惊喜轮播
router.get('/vuedemo/jx-banner', function (req, res, next) {
	var queryData = req.query;
	var sql =  supeSelect("select * from jx_banner",queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})


/*
router.get('/vuedemo/feature_all', function (req, res, next) {
    connectMysql('select * from feature' ,[''], (results) => {
        res.json(results);
        res.end();
    })
})
router.route('/vuedemo/get_category_one').get(function (req, res, next) {
    var queryData = req.query;
    sql =  supeSelect('select * from category_one',queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(results);
        res.end();
    })
})

router.route('/vuedemo/get_category_two').get(function (req, res, next) {
    var queryData = req.query;
    sql =  supeSelect('select * from category_one',queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(results);
        res.end();
    })
})

router.route('/vuedemo/get_category_three').get(function (req, res, next) {
    var queryData = req.query;
    sql =  supeSelect('select * from category_three',queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(results);
        res.end();
    })
})

*/
//京东 功能视图 show字段  1为页面中显示的，0在全部按钮中显示的
router.get('/vuedemo/jd_feature', function (req, res, next) {
    var queryData = req.query;
	var sql =  supeSelect('select * from jd_feature',queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//惊喜 功能视图 show字段 
router.get('/vuedemo/jx_feature', function (req, res, next) {
    var queryData = req.query;
	var sql =  supeSelect('select * from jx_feature',queryData);
    connectMysql(sql ,[''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//jd 一级分类
router.route('/vuedemo/get_jd_category_one').get(function (req, res, next) {
    var queryData = req.query;
    sql = supeSelect('select * from jd_category_one', queryData);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//jd 二级分类
router.route('/vuedemo/get_jd_category_two').get(function (req, res, next) {
    var queryData = req.query;
    sql = supeSelect('select * from jd_category_two', queryData);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//jd 三级分类
router.route('/vuedemo/get_jd_category_three').get(function (req, res, next) {
    var queryData = req.query;
    sql = supeSelect('select * from jd_category_three', queryData);
	sql = setPage(sql,queryData.page, queryData.pagesize)
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
// 根据一级分类查二级，根据二级查三级 取到 三维数组
router.route('/vuedemo/get_jd_category_max').get(function (req, res, next) {
    var maxData = [];
    var queryData = req.query;
    var mustKey = ['c1_id'];
    if(lostKeyStop(res,mustKey,queryData))return;
    function get1() {
        var sql = 'select * from jd_category_one ';
        sql = supeSelect(sql, queryData);
        connectMysql(sql, [''], (results) => {
            maxData = results;
            console.log(1)
            get2();
        });
    }
    function get2() {
        var sql = 'select * from jd_category_two';
        var ind = 0;
        for (var i of maxData) {
            var queryObj = { c1_id: i.c1_id };
            connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                console.log(1)
                maxData.map(item => {
                    if (results.length > 0 && item.c1_id == results[0].c1_id) {
                        item.c1_child = results;
                    }
                });
                ind++;
                if (ind == maxData.length) {
                    console.log(maxData);
                    get3();
                }
            })
        }
    }
    function get3() {
        var sql = 'select * from jd_category_three';
        var ind1 = 0;
        var ind = 0;
        for (var e of maxData) {
            if (e.c1_child != undefined) {
                ind1 += e.c1_child.length;
                for (var i of e.c1_child) {
                    var queryObj = { c1_id: i.c1_id, c2_id: i.c2_id };
                
                    connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                        console.log(3)
                        maxData.map(item => {
                            if (item.c1_child != undefined) {
                                item.c1_child.map(citem => {
                                    if (results.length > 0 && citem.c1_id == results[0].c1_id && results[0].c2_id == citem.c2_id) {
                                        citem.c2_child = results;
                                    }
                                })
                            }
                        });
                        ind++;
                        if (ind == ind1) {
                            res.json(pushOk(maxData));
                            res.end();
                        }
                    })
                }
            }

        }
    }
    get1();
})
//用户注册
router.route('/vuedemo/land').post(function (req, res, next) {
    var queryData = req.body;
    var mustKey = ['actionKey' ,  'telphone'];
    if (lostKeyStop(res, mustKey, queryData)) return;
    if (queryData.actionKey == 'account') {
        var mustKey = ['username', 'password', 'email'];
        if (lostKeyStop(res, mustKey, queryData)) return;
        connectMysql(`select * from user where \`name\`=${queryData.username}`, [''], (results) => {
            if (results.length <= 0) {
                connectMysql(`select * from user where \`tel\`=${queryData.telphone}`, [''], (results) => {
                    if (results.length <= 0) {
                        connectMysql(`select * from user where \`email\`=${queryData.email}`, [''], (results) => {
                            if (results.length <= 0) {
                                goLogin({
                                    tel: queryData.telphone,
                                    name: queryData.username,
                                    email: queryData.email,
                                    pwd: queryData.password,
                                });
                            } else {
                                res.json(pushError('邮箱已被绑定'));
                                res.end();
                            }
                        });
                    } else {
                        res.json(pushError('手机号码已被注册'));
                        res.end();
                    }
                });
            } else {
                res.json(pushError('用户名已存在'));
                res.end();
            }
        });
    }
    if (queryData.actionKey == 'shortmsg') {
        connectMysql(`select * from user where \`tel\`=${queryData.telphone}`, [''], (results) => {
            if (results.length <= 0) {
                goLogin({ tel: queryData.telphone, name: '', email: '', pwd: '' });
            } else {
                res.json(pushError('手机号码已被注册'));
                res.end();
            }
        });
    }
    function goLogin(qdata) {
        var sql = supeInsert('INSERT INTO user', qdata);
		console.log(sql);
        connectMysql(sql, [''], (results) => {
            res.json(pushOk([]));
            res.end();
        });
    }

})
// 新 用户 注册 -----  只有手机号注册
router.route('/vuedemo/register').post(function (req, res, next) {
	console.log(`\n register - 新用户手机号注册  `);
    var queryData = req.body;
    var mustKey = ['telphone', 'password','areacode'];
    if (lostKeyStop(res, mustKey, queryData)) return;
    connectMysql(`select * from user where \`tel\`=${queryData.telphone}`, [''], (results) => {
		if (results.length <= 0) {
			let obj='qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
			let user_name = obj[parseInt(Math.random()*obj.length)]+ queryData.telphone;
			goLogin({ 
				area_code: queryData.areacode, 
				tel: queryData.telphone, 
				name: user_name, 
				email: '', 
				pwd: queryData.password 
			});
		} else {
			res.json(pushError('手机号码已被注册'));
			res.end();
		}
    });
    function goLogin(qdata) {
        var sql = supeInsert('INSERT INTO user', qdata);
        connectMysql(sql, [''], (results) => {
            res.json(pushOk([]));
            res.end();
        });
    }

})
//用户登录
router.route('/vuedemo/land').post(function (req, res, next) {
	console.log(`\n land - 用户登录`);
    var queryData = req.body;
    var mustKey = ['actionKey'];
    if (lostKeyStop(res, mustKey, queryData)) return;
    if (queryData.actionKey == 'account') {
        var mustKey = ['username', 'password'];
        if (lostKeyStop(res, mustKey, queryData)) return;
        connectMysql(`select \`id\`,\`name\`,\`collectShop\`,autocode from user where \`pwd\`='${queryData.password}' and (\`name\`='${queryData.username}' or \`tel\`='${queryData.username}' or \`email\`='${queryData.username}'  )`, [''], (results) => {
            if (results.length <= 0) {
				connectMysql(`select * from user where \`name\`=${queryData.username} or \`tel\`=${queryData.username} or \`email\`=${queryData.username} `, [''], (results2) => {
					if (results2.length <= 0) {
						res.json(pushError('用户 no 被注册'));
						res.end();
					} else {
						res.json(pushError('用户名或密码错误'));
						res.end();
					}
				});
                
            } else {
				var userdata = results[0];
				var getaddsql = `select * from address where user_id = '${userdata.id}' and \`default\` = '1' `;
				
				
				
				connectMysql(getaddsql, [''], (result1) => {
					var addr = null;
					if(result1.length>0){
						addr = result1[0];
					}
					var resobg = pushOk([]);
					var autocode = creatId();
					resobg.data={};
					resobg.data.user = userdata;
					resobg.data.defaddr = addr;
					//resobg.data.autocode=autocode;
					resobg.data.user.autocode= autocode;
					var setaucode = `update user set autocode = '${autocode}',lastlandtime = now() where id = '${userdata.id}'`;
					connectMysql(setaucode, [''], (result1) => {
						res.json(resobg);
						res.end();
					});
				});
				
				
            }
        });
    }



	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}

})

router.route('/vuedemo/getuser').post(function (req, res, next) {
	console.log(`\n getuser - 获取用户信息`);
	var queryData = req.body;
	var mustKey = ['id'];
    if (lostKeyStop(res, mustKey, queryData)) return;
    connectMysql(`select * from user where  id = ${queryData.id} `, [''], (results) => {
        res.json(pushOk(results[0]));
		console.log(pushOk(results[0]));
		res.end();	
    });
})


// `select * from user where  id = ${queryData.id} `


//授权登录
router.route('/vuedemo/empowerland').post(function (req, res, next) {
	console.log(`\n empowerland - 授权登录`);
    var queryData = req.body;
    var mustKey = ['autocode'];
    if (lostKeyStop(res, mustKey, queryData)) return;
		//console.log(queryData.autocode);
        connectMysql(`select \`id\`,\`name\`,\`collectShop\`,autocode from user where \`autocode\`='${queryData.autocode}'`, [''], (results) => {
        //connectMysql(`select \`id\`,\`name\`,lastlandtime from user where \`autocode\`='${queryData.autocode}'`, [''], (results) => {
			if (results.length <= 0) {
				res.json(pushError('自动登录失败，请重新登录'));
				res.end();
            } else {
				var userdata = results[0];
				var getaddsql = `select * from address where user_id = '${userdata.id}' and \`default\` = '1' `;
				connectMysql(getaddsql, [''], (result1) => {
					var addr = null;
					if(result1.length>0){
						addr = result1[0];
					}
					var resobg = pushOk([]);
					var autocode = creatId();	
					resobg.data={};
					resobg.data.user = userdata;
					resobg.data.defaddr = addr;
					resobg.data.user.autocode= autocode;
					var setaucode = `update user set autocode = '${autocode}'  where id = '${userdata.id}'`;
					connectMysql(setaucode, [''], (result1) => {
						res.json(resobg);
						res.end();
					});
				});
				
				
            }
        });
    

	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}
	function pdtime(data){
		 var timeOld = new Date(data.lastlandtime).getTime();
		 var timeNow = new Date().getTime();
		 //console.log(timeNow - timeOld);
		 if((timeNow - timeOld) >(LandOverTime*24*60*60*1000)){
			return true;
		 }else{
			return false;
		 }
	}
})


//X天内免登录
router.route('/vuedemo/autoland').post(function (req, res, next) {
	console.log(`\n autoland - 自动登录`);
    var queryData = req.body;
    var mustKey = ['autocode'];
    if (lostKeyStop(res, mustKey, queryData)) return;
		//console.log(queryData.autocode);
        connectMysql(`select \`id\`,\`name\`,\`collectShop\`,autocode from user where \`autocode\`='${queryData.autocode}'`, [''], (results) => {
		
            if (results.length <= 0) {
				res.json(pushError('自动登录失败，请重新登录'));
				res.end();
            } else if(pdtime(results[0])) {
				var obj = pushError('自动登录失败 距离上次登录时间超过7天');
				obj.code = 401;
				res.json(obj);
				res.end();
            } else {
				var userdata = results[0];
				
				var getaddsql = `select * from address where user_id = '${userdata.id}' and \`default\` = '1' `;
				connectMysql(getaddsql, [''], (result1) => {
					var addr = null;
					if(result1.length>0){
						addr = result1[0];
					}
					var resobg = pushOk([]);
					resobg.data={};
					resobg.data.user = userdata;
					resobg.data.defaddr = addr;
					res.json(resobg);
					res.end();
					
				});
				
				
            }
        });
    

	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}
	function pdtime(data){
		 var timeOld = new Date(data.lastlandtime).getTime();
		 var timeNow = new Date().getTime();
		 //console.log(timeNow - timeOld);
		 if((timeNow - timeOld) >(LandOverTime*24*60*60*1000)){
			return true;
		 }else{
			return false;
		 }
	}
})
/*
router.route('/vuedemo/autoland1').post(function (req, res, next) {
	console.log(`\n autoland - 自动登录`);
    var queryData = req.body;
    var mustKey = ['autocode'];
    if (lostKeyStop(res, mustKey, queryData)) return;
		//console.log(queryData.autocode);
        connectMysql(`select * from user where \`autocode\`='${queryData.autocode}'`, [''], (results) => {
            if (results.length <= 0) {
				res.json(pushError('自动登录失败，请重新登录'));
				res.end();
            } else {
				var userdata = results[0];
				var getaddsql = `select * from address where user_id = '${userdata.id}' and \`default\` = '1' `;
				connectMysql(getaddsql, [''], (result1) => {
					var addr = null;
					if(result1.length>0){
						addr = result1[0];
					}
					var resobg = pushOk([]);
					var autocode = creatId();
					resobg.data={};
					resobg.data.user = userdata;
					resobg.data.defaddr = addr;
				//	resobg.data.autocode=autocode;
					resobg.data.user.autocode= autocode;
					var setaucode = `update user set autocode = '${autocode}' where id = '${userdata.id}'`;
					connectMysql(setaucode, [''], (result1) => {
						res.json(resobg);
						res.end();
					});
				});
				
				
            }
        });
    

	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}

})
*/

//supeUpadte


router.route('/vuedemo/update_userdet').post(function (req, res, next) {
	var queryData = req.body;
	var tabName='user';
	var mustKey = ['id'];
    if (lostKeyStop(res, mustKey, queryData)) return;
	var kObj = queryData;
	var vObj = {id:queryData.id};
	var upsql = supeUpadte(tabName,kObj,vObj);
	
	connectMysql(upsql, [''], (results) => {

		connectMysql(`select * from user where id = ${queryData.id}`, [''], (result) => {

				var obj = pushOk(result[0]);
				obj.msg='修改成功';
                res.json(obj);
                res.end();
		});
				
    });
});


router.route('/vuedemo/land_have_telphone').get(function (req, res, next) {
	console.log(`\n land_have_telphone`);
    var queryData = req.query;
    var mustKey = ['telphone'];
	console.log(queryData);
    if (lostKeyStop(res, mustKey, queryData)) return;
	connectMysql(`select * from user where \`tel\`='${queryData.telphone}' `, [''], (results) => {
            if (results.length > 0) {
				var obj = pushError('手机号已被注册');
				obj.data = results[0]
				res.json(obj);
				res.end();
            } else {
				var obj = pushOk([]);
				obj.msg='可以注册';
                res.json(obj);
                res.end();
            }
        });

})

router.route('/vuedemo/land_have_email').get(function (req, res, next) {
	console.log(`\n land_have_email`);
    var queryData = req.query;
    var mustKey = ['email'];
    if (lostKeyStop(res, mustKey, queryData)) return;
	connectMysql(`select * from user where \`email\`='${queryData.email}' `, [''], (results) => {
            if (results.length > 0) {
				res.json(pushError('邮箱已被使用'));
				res.end();
            } else {
				var obj = pushOk([]);
				obj.msg='可以注册';
                res.json(obj);
                res.end();
            }
        });

})

router.route('/vuedemo/land_have_username').get(function (req, res, next) {
	console.log(`\n land_have_username`);
    var queryData = req.query;
    var mustKey = ['username'];
    if (lostKeyStop(res, mustKey, queryData)) return;
	connectMysql(`select * from user where \`name\`='${queryData.username}' `, [''], (results) => {
            if (results.length > 0) {
				res.json(pushError('用户名已被使用'));
				res.end();
            } else {
				var obj = pushOk([]);
				obj.msg='可以注册';
                res.json(obj);
                res.end();
            }
        });

})




//
router.route('/vuedemo/get_interface').post(function (req, res, next) {
   var queryData = req.body;

	connectMysql(`select * from \`interface\` order by orderkey `, [''], (result) => {
			
				res.json(pushOk(result));
				res.end();
		});
   

})

router.route('/blog/get_blog').post(function (req, res, next) {
	var queryData = req.body;
	var thatSql = 'SELECT * FROM all_blog';
	console.log(1);
	thatSql =  supeSelect(thatSql, queryData);
	console.log(thatSql);
	connectMysqlBolg(thatSql,[''], (result) => {
		console.log(result);
			res.json(pushOk(result));
			res.end();
	});
})

router.route('/blog/set_blog').post(function (req, res, next) {	
	
	var queryData = req.body;
	var thatSql = 'INSERT INTO all_blog';
	thatSql = supeInsert(thatSql, queryData);
	connectMysqlBolg(thatSql,[''], (result) => {
		res.json(pushOk(result));
		res.end();
		//SELECT * FROM all_blog
	});
})

router.route('/blog/get_blog_classfly').post(function (req, res, next) {
	var thatSql = 'SELECT * FROM classfly';
	connectMysqlBolg(thatSql,[''], (result) => {
			res.json(pushOk(result));
			res.end();
	});
})

router.route('/vuedemo/get_inter_byid').post(function (req, res, next) {
   var queryData = req.body;
	connectMysql(`select * from \`inter_key\` where inter_id = ${queryData.id}  `, [''], (result) => {
		var keys = result;
		connectMysql(`select * from \`inter_val\` where inter_id = ${queryData.id}  `, [''], (results) => {
				var vals = results;
				var obj = pushOk([]);
				obj.data={};
				obj.data.keys = keys;
				obj.data.vals = vals;
				res.json(obj);
				res.end();
		});		
	});
   

})

router.route('/vuedemo/creat_inter').post(function (req, res, next) {
   var queryData = req.body;
	
	var cre_inter = supeInsert(`INSERT INTO \`interface\` `, queryData.interface);
	var cre_key = supeInsert(`INSERT INTO inter_key `, queryData.key);
	var cre_val = supeInsert(`INSERT INTO inter_val `, queryData.val);
	connectMysql(cre_inter, [''], (result) => {
		connectMysql(cre_key, [''], (result) => {
			connectMysql(cre_val, [''], (result) => {
				var obj = pushOk([]);
				res.json(obj);
				res.end();
			});
		});
	});
   

})

//获取店铺
router.route('/vuedemo/get_shops').get(function (req, res, next) {
	console.log(`\n get_goodsDet 获取店铺`);
	 var queryData = req.query;
	 var thatSql = 'SELECT * FROM jd_shops';
	thatSql =  supeSelect(thatSql, queryData);
	connectMysql(thatSql, [''], (results) => {
			var resOk = pushOk(results);
			resOk.msg = '获取商铺数据成功';
			res.json(resOk);
			res.end();
	});
})

//获取店铺所有商品
router.route('/vuedemo/get_shop_goods').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['shop_id'];
	console.log(`\n get_shop_goods 获取店铺中商品`)
    if(lostKeyStop(res,mustKey,queryData))return;
    var sql = `SELECT d.* FROM goods_all AS d
        LEFT JOIN jd_category_one AS jd1 ON d.c1_id_jd = jd1.c1_id
        LEFT JOIN jd_category_two AS jd2 ON d.c2_id_jd = jd2.c2_id
        LEFT JOIN jd_category_three AS jd3 ON d.c1_id_jd = jd3.c3_id
        LEFT JOIN jx_category_one AS jx1 ON d.c1_id_jx = jx1.c1_id
        LEFT JOIN jx_category_two AS jx2 ON d.c2_id_jx = jx2.c2_id
        LEFT JOIN jx_category_three AS jx3 ON d.c1_id_jx = jx3.c3_id
		where d.shop_id = ${queryData.shop_id}
	`;
	sql=setPage(sql,queryData.page,queryData.pagesize);
	//if(queryData.page==undefined)msg+='所有数据;';	    

    connectMysql(sql, [''], (results) => {
	   var obj = pushOk(results);
		obj.msg = '';
	    if(queryData.page!=undefined){
			obj.page=queryData.page;
			obj.msg+=`店铺商品数据第${obj.page}页 每页`
			if(queryData.pagesize!=undefined){
				obj.pagesize=queryData.pagesize;
				
			}else{
				obj.pagesize=50
			};
			obj.msg+=`${obj.pagesize}条`
		}else{
			obj.msg = '商铺中所有商铺';
		}	    
        res.json(obj);
        res.end();
    });

})

//搜索商品
router.route('/vuedemo/get_goods').get(function (req, res, next) {
    var queryData = req.query;
    var sql = `SELECT d.* FROM goods_all AS d
        LEFT JOIN jd_category_one AS jd1 ON d.c1_id_jd = jd1.c1_id
        LEFT JOIN jd_category_two AS jd2 ON d.c2_id_jd = jd2.c2_id
        LEFT JOIN jd_category_three AS jd3 ON d.c1_id_jd = jd3.c3_id
        LEFT JOIN jx_category_one AS jx1 ON d.c1_id_jx = jx1.c1_id
        LEFT JOIN jx_category_two AS jx2 ON d.c2_id_jx = jx2.c2_id
        LEFT JOIN jx_category_three AS jx3 ON d.c1_id_jx = jx3.c3_id`;
	var msg = '获取goods数据';
	//console.log(queryData);
	
    function like(sql, where,name) {
		var w = 'and';
		if(where)w = 'where';
        sql += ` ${w} (d.name LIKE '%${name}%' OR d.c_keyword LIKE '%${name}%' OR jd1.c1_name LIKE '%${name}%' OR jd2.c2_name LIKE '%${name}%' OR jd3.c3_name LIKE '%${name}%' OR jx1.c1_name LIKE '%${name}%' OR jx2.c2_name LIKE '%${name}%' OR jx3.c3_name LIKE '%${name}%') `
        return sql;
    }
    if(queryData.exact!=undefined){
		if(typeof queryData.exact=='string'){
			try{
				queryData.exact = JSON.parse(queryData.exact)
			}catch(e){
				res.json(pushError('exact 数据格式有误！！！'));
				res.end();
			}
		}

        sql = supeSelect(sql,queryData.exact)
		msg+=' 精准查询...; '
    }
    if (queryData.like != undefined) {
       // if(queryData.exact!=undefined)sql+=` and `;
		var where = (queryData.exact==undefined || queryData.exact=={});
        sql = like(sql, where,queryData.like)
		msg+=' 模糊查询 -'+queryData.like+'-;';
    }
	if(queryData.maxMoney!=undefined && queryData.minMoney!=undefined){
			if(
				(queryData.exact==undefined || queryData.exact=={})
				&&
				(queryData.like == undefined)
			){sql+=' where '}else{sql+=' and '}
			if(queryData.maxMoney!='' &&  queryData.minMoney!=''){
				sql+=` d.money_now < ${queryData.maxMoney} and d.money_now > ${queryData.minMoney} `
			}else if(queryData.maxMoney!='' &&  queryData.minMoney==''){
				sql+=` d.money_now < ${queryData.maxMoney} `;
			}else if(queryData.maxMoney=='' &&  queryData.minMoney!=''){
				sql+=` d.money_now > ${queryData.minMoney} `;
			}
		}
    if(queryData.order!=undefined){
		//msg+=' 根据 ';
        //for(var x in queryData.order){
		//	var item = queryData.order[x];
		//	var name = item.name;
		//	var desc = '';
		//	if(item)
		//	if(x==0) sql+=`order by d.${item}`;
		//	if(x!=0) sql+=`,d.${item}`;
		//	msg+=` \`${item}\` `;
        //}
		//msg+='排序;';
		var f = true;
		
		for(var x in queryData.order){
			var name = x;
			
			var val = queryData.order[x];
			var rule= '';
			if(val=='UtoD')rule='desc';
			if(val=='DtoU')rule='';
			if(f){
				sql+=`order by d.${name} ${rule}`;
				f=false;
			}else{
				sql+=`,d.${name} ${rule}`;
			}
		}
    }
   sql=setPage(sql,queryData.page,queryData.pagesize);
	if(queryData.page==undefined)msg+='所有数据;';	    

    connectMysql(sql, [''], (results) => {
	   var obj = pushOk(results);
	   obj.msg = msg;
	    if(queryData.page!=undefined){
			obj.page=queryData.page;
				if(queryData.pagesize!=undefined){obj.pagesize=queryData.pagesize}else{obj.pagesize=50};
				};	    
        res.json(obj);
        res.end();
    });

})

//获取商品详情
router.route('/vuedemo/get_goodsDet').get(function (req, res, next) {
	console.log(`\n get_goodsDet 获取商品详情`);
    var queryData = req.query;
	var mustKey = ['goods_id'];
	if(lostKeyStop(res,mustKey,queryData)) return;
	var msg = '获取商品详情';
	//console.log(queryData);
	console.log(0);
	var resOk = pushOk({});
	resOk.msg = msg;
	getOneGoods();
	function getOneGoods(){
		var sql = `SELECT * FROM goods_all where id = ${queryData.goods_id}`;
		connectMysql(sql, [''], (results) => {
			if(results.length>0){
				resOk.data.goodsData = results[0];
				resOk.data.goodsData.img_detalis_list = resOk.data.goodsData.img_detalis_list.split(',');
				getRelation();
			}else{
				res.json(pushError(	`没有id为${queryData.goods_id}的商品`));
				res.end();
			}
		});
	}
	function getRelation(){
		var obj = {};
		var thatSql = 'SELECT * FROM goods_all';
		obj.shop_id = resOk.data.goodsData.shop_id;
		obj.relation_keyword = resOk.data.goodsData.relation_keyword;
		thatSql =  supeSelect(thatSql, obj);
		connectMysql(thatSql, [''], (results) => {
			resOk.data.relationGoods = results;
			getsevaluate();
		});
	}
	function getsevaluate(){
		var obj = {};
		var thatSql = 'select * from goods_sevaluate';
		obj.goods_id = queryData.goods_id;
		thatSql =  supeSelect(thatSql, obj);
		thatSql = `${thatSql} ORDER BY EvaluationTime desc limit 1,3`
		connectMysql(thatSql, [''], (results) => {
			resOk.data.sevaluateDate = results;
			getNorms();
		});
	}
	function getNorms(){
		var obj = {};
		var thatSql = 'SELECT * FROM norms';
		obj.goods_id = queryData.goods_id;
		thatSql =  supeSelect(thatSql, obj);
		connectMysql(thatSql, [''], (results) => {
			resOk.data.norms = results;
			getShop();
		});
	}

	function getShop(){
		var obj = {};
		var thatSql = 'SELECT * FROM jd_shops';
		obj.id = resOk.data.goodsData.shop_id;
		thatSql =  supeSelect(thatSql, obj);
		connectMysql(thatSql, [''], (results) => {
			if(results.length>0){
				resOk.data.shopData = results[0];
			}else{
				resOk.data.shopData = {};
			}
			
			goBack();
		});
	}
	function goBack(){
		//console.log(resOk);
		res.json(resOk);
		res.end();
	}
})
//获取商品评价
router.route('/vuedemo/get_goods_sevaluate').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['goods_id'];
	if(lostKeyStop(res,mustKey,queryData)) return;
    sql = supeSelect('select * from goods_sevaluate', queryData);
	var msg = '获取商品评价';
    connectMysql(sql, [''], (results) => {
		if(results.length>0){
			var obj = pushOk(results);
		}else{
			var obj = pushOk([]);
		}
		obj.msg = msg; 
        res.json(obj);
        res.end();
    })
})


//获取关联商品
router.route('/vuedemo/get_goods_relation').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['shop_id','relation_keyword'];
    if(lostKeyStop(res,mustKey,queryData))return;
    var sql = `SELECT * FROM goods_all where relation_keyword = ${queryData.relation_keyword} and shop_id = ${queryData.shop_id}`
	var msg = '获取goods表关联商品';
    connectMysql(sql, [''], (results) => {
		var obj = pushOk(results);
		obj.msg = msg; 
        res.json(obj);
        res.end();
    });
})

//获取商品规格
router.route('/vuedemo/get_norms').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['goods_id'];
    if(lostKeyStop(res,mustKey,queryData))return;
    var sql = `SELECT * FROM norms where goods_id = ${queryData.goods_id}`
	var msg = '获取商品规格';
    connectMysql(sql, [''], (results) => {
		var obj = pushOk(results);
		obj.msg = msg; 
        res.json(obj);
        res.end();
    });
})

/*
router.route('/vuedemo/get_jd_category_max').get(function (req, res, next) {
    
	//var queryData = null;
	//console.log(req.query);
	//if(req.query.c1_id) queryData = req.query
	//else queryData = {err:0}
	//console.log(queryData);
	var maxData = [];
    var queryData = req.query;
    var mustKey = ['c1_id'];
    if(lostKeyStop(res,mustKey,queryData))return;
    function get1() {
        var sql = 'select * from jd_category_one ';
        sql = supeSelect(sql, queryData);
        connectMysql(sql, [''], (results) => {
            maxData = results;
			get2();
        });
    }
    function get2() {
        var sql = 'select * from jd_category_two';
        var ind = 0;
        for (var i of maxData) {
            var queryObj = { c1_id: i.c1_id };
            connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                maxData.map(item => {
                    if (results.length > 0 && item.c1_id == results[0].c1_id) {
                        item.c1_child = results;
                    }
                });
                ind++;
				return;
                if (ind == maxData.length) {
                    get3();
                }
            })
        }
    }
    function get3() {
        var sql = 'select * from jd_category_three';
        var ind1 = 0;
        var ind = 0;
        for (var e of maxData) {
            if (e.c1_child != undefined) {
                ind1 += e.c1_child.length;
                for (var i of e.c1_child) {
                    var queryObj = { c1_id: i.c1_id, c2_id: i.c2_id };
                    connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                        maxData.map(item => {
                            if (item.c1_child != undefined) {
                                item.c1_child.map(citem => {
                                    if (results.length > 0 && citem.c1_id == results[0].c1_id && results[0].c2_id == citem.c2_id) {
                                        citem.c2_child = results;
                                    }
                                })
                            }
                        });
                        ind++;
                        if (ind == ind1) {
                            res.json(maxData);
                            res.end();
                        }
                    })
                }
            }

        }
    }
    get1();
})*/


//获取用户所有地址
router.route('/vuedemo/get_user_address').get(function (req, res, next) {
	console.log(`\n get_user_address 获取用户所有地址 `);
    var queryData = req.query;
	var mustKey = ['user_id'];
	var sql = 'SELECT id from address';
    //sql = supeSelect(sql3,queryData.goods);
	console.log(queryData);
    if(lostKeyStop(res,mustKey,queryData))return;
	if(queryData.address_id!='' && queryData.address_id!=undefined){
		sql = `SELECT * FROM address where user_id = '${queryData.user_id}' and id = '${queryData.address_id}'`
	}else{
		sql = `SELECT * FROM address where user_id = '${queryData.user_id}'`	
	}
    //var 
    connectMysql(sql, [''], (results) => {
		var obj = pushOk(results);
        res.json(obj);
        res.end();
    });
})

//增加用户收货地址
router.route('/vuedemo/creat_user_address').get(function (req, res, next) {
	console.log(`\n 增加用户收货地址`)
    var queryData = req.query;
	console.log(`\n creat_user_address 增加用户收货地址 `);
	var mustKey = ['user_id','takeover_tel','takeover_addr','takeover_name','takeover_label','default'];
    if(lostKeyStop(res,mustKey,queryData))return;
	var id =creatId();
	queryData.id = id;
	if(queryData.default == 0){
		var sql = supeInsert(`INSERT INTO address `, queryData);
		connectMysql(sql, [''], (results) => {
			var obj = pushOk({});
			obj.data.address = queryData;
			res.json(obj);
			res.end();
		});
	}else if(queryData.default == 1){
		var upother = `update address set \`default\` = 0 where user_id = '${queryData.user_id}'`;
		connectMysql(upother, [''], (result) => {
			var sql = supeInsert(`INSERT INTO address `, queryData);
			connectMysql(sql, [''], (results) => {
				var obj = pushOk({});
				obj.data.address = queryData;
				res.json(obj);
				res.end();
			});
		});
	}
	function getOneKey(){
		var num = parseInt( Math.random()*10 );
		return num.toString(10);
	}
    
	function creatId(){
		var idd = '';
		for(var i=0;i<10;i++){
			var nk = getOneKey();
			if(i==0 && nk=='0'){
				nk='1';
			}
			idd+= nk;
		}
		return idd;
	}
})

//删除用户收货地址
router.route('/vuedemo/delete_user_address').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['address_id'];
	
	console.log(`\n delete_user_address 删除用户收货地址 `);
    if(lostKeyStop(res,mustKey,queryData))return;
	var sql = ` delete  from address where id= ${queryData.address_id}`;
	connectMysql(sql, [''], (results) => {
        res.json(pushOk([]));
        res.end();
    })
})

//修改默认用户收货地址
router.route('/vuedemo/update_user_address_def').get(function (req, res, next) {
    var queryData = req.query;
	console.log(`\n update_user_address_def 修改默认用户收货地址 `);
	var mustKey = ['address_id','user_id'];
    if(lostKeyStop(res,mustKey,queryData))return;
		var upother = `update address set \`default\` = 0 where user_id = '${queryData.user_id}'`;
		connectMysql(upother, [''], (result) => {
			var upother = `update address set \`default\` = 1 where id = '${queryData.address_id}'`;
			connectMysql(upother, [''], (results) => {
				var obj = pushOk([]);
				res.json(obj);
				res.end();
			});
		});
	
})

//修改用户详细收货地址
router.route('/vuedemo/update_user_address').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['address_id','user_id','takeover_tel','takeover_label','takeover_addr','takeover_name','default'];
	console.log('修改用户详细收货地址')
    if(lostKeyStop(res,mustKey,queryData))return;
	if(queryData.default == 0){
		var sql = `update address set 
		takeover_tel = '${queryData.takeover_tel}' , 
		takeover_addr = '${queryData.takeover_addr}' ,
		takeover_label = '${queryData.takeover_label}' ,
		takeover_name = '${queryData.takeover_name}' ,
		\`default\` = 1
		where 
		id = '${queryData.address_id}'`;
		connectMysql(sql, [''], (result) => {
			var obj = pushOk({});
			obj.data.address = queryData;
			res.json(obj);
			res.end();
		});
	}else if(queryData.default == 1){
		var upother = `update address set \`default\` = 0 where user_id = '${queryData.user_id}'`;
		connectMysql(upother, [''], (result) => {
			var sql = `update address set 
			takeover_tel = '${queryData.takeover_tel}' , 
			takeover_addr = '${queryData.takeover_addr}' ,
			takeover_label = '${queryData.takeover_label}' ,
			takeover_name = '${queryData.takeover_name}' ,
			\`default\` = 1
			where 
			id = '${queryData.address_id}'`;
			connectMysql(sql, [''], (result) => {
				var obj = pushOk({});
				obj.data.address = queryData;
				res.json(obj);
				res.end();
			});
		});
	}
	
})

//惊喜分类表1
router.route('/vuedemo/get_jx_category_one').get(function (req, res, next) {
    var queryData = req.query;
    sql = supeSelect('select * from jx_category_one', queryData);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//惊喜分类表2
router.route('/vuedemo/get_jd_category_two').get(function (req, res, next) {
    var queryData = req.query;
    sql = supeSelect('select * from jx_category_two', queryData);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//惊喜分类表3
router.route('/vuedemo/get_jx_category_three').get(function (req, res, next) {
    var queryData = req.query;   
    sql = supeSelect('select * from jx_category_three', queryData);
	if(queryData.page!= undefined)sql = setPage(sql,page.index,page.size);
    connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})

//分类表所有(1,2,3)
router.route('/vuedemo/get_jx_category_max').get(function (req, res, next) {
    var maxData = [];
    var maxData = [];
    var queryData = req.query;
    var mustKey = ['c1_id'];
    if(lostKeyStop(res,mustKey,queryData))return;
    function get1() {
        var sql = 'select * from jx_category_one ';
        sql = supeSelect(sql, queryData);
        connectMysql(sql, [''], (results) => {
            maxData = results;
            console.log(1)
            get2();
        });
    }
    function get2() {
        var sql = 'select * from jx_category_two';
        var ind = 0;
        for (var i of maxData) {
            var queryObj = { c1_id: i.c1_id };
            connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                maxData.map(item => {
                    if (results.length > 0 && item.c1_id == results[0].c1_id) {
                        item.c1_child = results;
                    }
                });
                ind++;
                if (ind == maxData.length) {
                    console.log(maxData);
                    get3();

                }
            })
        }
    }
    function get3() {
        var sql = 'select * from jx_category_three';
        var ind1 = 0;
        var ind = 0;
        for (var e of maxData) {
            if (e.c1_child != undefined) {
                ind1 += e.c1_child.length;
                for (var i of e.c1_child) {
                    var queryObj = { c1_id: i.c1_id, c2_id: i.c2_id };
                    connectMysql(supeSelect(sql, queryObj), [''], (results) => {
                        maxData.map(item => {
                            if (item.c1_child != undefined) {
                                item.c1_child.map(citem => {
                                    if (results.length > 0 && citem.c1_id == results[0].c1_id && results[0].c2_id == citem.c2_id) {
                                        citem.c2_child = results;
                                    }
                                })
                            }
                        });
                        ind++;
                        if (ind == ind1) {
                            res.json(maxData);
                            res.end();
                        }
                    })
                }
            }

        }
    }
    get1();
})

// 获取购物车商品
router.route('/vuedemo/get_shopcart').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['user_id'];
	if(lostKeyStop(res,mustKey,queryData))return;
	var sql = `	SELECT
				c.id as id , g.id as goods_id , g.name as goods_name ,s.name as shop_name, g.img_cover , g.money_now , g.money_old , g.hot_keyword , g.shop_id ,c.num ,c.user_id , c.norm ,c.updatetime,c.ischeck,c.takeover_addr
				FROM
				shopcarts AS c
				LEFT JOIN goods_all AS g ON g.id = c.goods_id
				LEFT JOIN jd_shops AS s ON s.id = g.shop_id
				WHERE
				user_id = ${queryData.user_id} and
				c.iswhere='shopcar'
				ORDER BY c.updatetime DESC
				
				`
		connectMysql(sql, [''], (results) => {
        res.json(pushOk(results));
        res.end();
    })
})
//修改购物车商品数据
router.route('/vuedemo/update_shopcart').post(function (req, res, next) {
    var queryData = req.body;
	
	if(lostKeyStop(res,['id','num','norm','ischeck','takeover_addr'],queryData))return;
	var sql = `update shopcarts set num = ${queryData.num} , norm = '${queryData.norm}' , ischeck = '${queryData.ischeck}' ,takeover_addr = '${queryData.takeover_addr}' where id= ${queryData.id}`;
	connectMysql(sql, [''], (results) => {
        res.json(pushOk([]));
        res.end();
    })
})
//删除购物车商品
router.route('/vuedemo/delete_shopcart').post(function (req, res, next) {
    var queryData = req.body;
	if(lostKeyStop(res,['id'],queryData))return;
	var sql = ` delete  from shopcarts where id= ${queryData.id}`;
	connectMysql(sql, [''], (results) => {
        res.json(pushOk([]));
        res.end();
    })
})
//替换商品
router.route('/vuedemo/set_shopcart').post(function (req, res, next) {
    var obj = req.body;
	console.log(obj);
		var mustKey = ['user_id','goods_id','num','norm','takeover_addr'];
		if(lostKeyStop(res,mustKey,obj))return;
		obj.ischeck = 1;
		var sql1 = `select * from  shopcarts where user_id = '${obj.user_id}' and goods_id='${obj.goods_id}' and norm = '${obj.norm}'`;
		
		connectMysql(sql1, [''], (results) => {
			var sql2 = supeInsert('INSERT INTO shopcarts', obj);
			if(results.length > 0){
				var num = parseInt(results[0].num)  + parseInt(obj.num) ;
				sql2 = `update shopcarts set num = ${num},ischeck=1 where id= ${results[0].id}`;
			}
			connectMysql(sql2, [''], (results) => {
					res.json(pushOk([]));
					res.end();
			})
		})
	
	
	
})

router.route('/vuedemo/buy_goods').post(function (req, res, next) {
		console.log('buy_goods')
		var queryData = req.body;
		var mustKey = ['user_id','goods_id','num','norm','takeover_addr'];
		if(lostKeyStop(res,mustKey,queryData))return;
		var cre_id = creatId();
		function getOneKey(){
			var num = parseInt( Math.random()*10);
			return num.toString(10);
		}
		function creatId(){
			var idd = '';
			for(var i=0;i<18;i++){
				var k = getOneKey();
				if(k=='0')k='1';
				idd+=k;
			}
			return idd;
		}
		var sql = `INSERT INTO \`order\` `;
		var orderObj = {id:cre_id,user_id:queryData.user_id,state:0};//待确认状态
		sql = supeInsert(sql,orderObj);
		//sql += 'and creat_time = now()'
		connectMysql(sql, [''], (results) => {
			doNext();
		});
		function doNext(){
			var obj = queryData;
			obj.ischeck = 0;
			obj.iswhere = 'order';
			obj.order_id = cre_id;
			var sql2 = supeInsert('INSERT INTO shopcarts', obj);
			connectMysql(sql2, [''], (results) => {
					res.json(pushOk({order_id:cre_id}));
					res.end();
			})
		}
})

//京东tabbar
router.get('/vuedemo/jd_tabbar', function (req, res, next) {
    connectMysql("select * from jd_tabbar", '', (results) => {
        res.json(pushOk(results));
		res.end()
    })
})
//惊喜tabbar
router.get('/vuedemo/jx_tabbar', function (req, res, next) {
    connectMysql("select * from jx_tabbar", '', (results) => {
        res.json(pushOk(results));
		res.end()
    })
})

//商户存商品接口
router.route('/vuedemo/set_goods').get(function (req, res, next) {
    var queryData = req.query;
    var sql = `INSERT INTO goods_all`;
    // queryData.goods={};
    // queryData.goods.name = 1;
	console.log(queryData.goods);
	function getOneKey(){
		var num = parseInt( Math.random()*37 );
		return num.toString(36);
	}
    var id =creatId();
	function creatId(){
		var idd = '';
		for(var i=0;i<10;i++){
			idd+= getOneKey();
		}
		return idd;
	}
	//console.log(id);
    queryData.goods.id = id;
	//console.log(queryData.goods);
    sql = supeInsert(sql,queryData.goods);
    //sql += `;SELECT LAST_INSERT_ID() as id;`
  //  console.log(sql);
   
   
    // queryData.norms = [
    //     {
    //         nor_name: 'x',
    //         list: [
    //             { name: 'y', img: 'y', money: 'y' }
    //         ]
    //     }
    // ]
    connectMysql(sql, [''], (results) => {
       // connectMysql('SELECT LAST_INSERT_ID() as id', [''], (results) => {
           //var sql3 = 'SELECT id from goods_all';
          // sql3 = supeSelect(sql3,queryData.goods);
         //  connectMysql(sql, [''], (results) => {
            // connectMysql('SELECT LAST_INSERT_ID() as id', [''], (results) => {
              //  var sql3 = 'SELECT id from goods_all';
             //   sql3 = supeSelect(sql3,queryData.goods);
             //if(queryData.norms.length>0){
                doNext();
            //// }else{
             //   res.json({'ok':'ok'});
             //   res.end();
             //}
                
            // });
            
        
            //doNext(results[0].id);
       // });
       
    });
    var allNum = 0;
    var indx = 0;
    function doNext(){
		  //console.log(3);
       // console.log(queryData);
		if(queryData.norms == undefined){
			res.json({'ok':'ok'});
            res.end();
			return;
		}
       // console.log(queryData.norms[0].list );
        for( x of queryData.norms ){
            // var qd = x.list;
            allNum+=x.list.length;
            for(y of x.list){
                var obj ={};
                obj.goods_id = queryData.goods.id;
                obj.ggname = x.nor_name;
                obj.ggimg = y.img;
                obj.ggmoney = y.money;
                obj.ggitem = y.name;
                var sql2 =  supeInsert(`INSERT INTO norms `,obj);
                //console.log(sql2);
                connectMysql(sql2, [''], (results) => {
                    console.log(results)
                    indx++;
                    if(indx == allNum){
                        res.json({'ok':'ok'});
                        res.end();
                    }
                });
            }
        }
    }
})



router.route('/vuedemo/creat_order').post(function (req, res, next) {
    var queryData = req.body;
	console.log('/vuedemo/creat_order');
	var mustKey = ['shopcarts_id','user_id','takeover_addr'];
	console.log(queryData);
	if(lostKeyStop(res,mustKey,queryData))return;
	var cre_id = creatId();
	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}
    var sql = `INSERT INTO \`order\` `;
	var orderObj = {id:cre_id,user_id:queryData.user_id,state:0};//待确认状态

	sql = supeInsert(sql,orderObj);
	console.log(sql);
	connectMysql(sql, [''], (results) => {
        doNext();
    });
	function doNext(){
		//var upobj = {id:queryData.chopcarts_id};
		var upsql = `UPDATE shopcarts SET iswhere = 'order',order_id='${cre_id}',takeover_addr ='${queryData.takeover_addr}'  where id in (`;
		var len = queryData.shopcarts_id.length;
		for(var i=0;i<len;i++){
			var item = queryData.shopcarts_id[i];
			if(i!=len-1)upsql+=`'${item}',`;
			if(i==len-1)upsql+=`'${item}')`;
		}
		console.log(upsql);
		connectMysql(upsql, [''], (results) => {
			res.json(pushOk({order_id:cre_id}));
			res.end();
		});
    }
})
var path = require('path');
//生成订单
router.route('/vuedemo/creat_order').get(function (req, res, next) {
    var queryData = req.query;
	console.log('/vuedemo/creat_order');
	var mustKey = ['shopcarts_id','user_id'];
	console.log(queryData);
	if(lostKeyStop(res,mustKey,queryData))return;
	var cre_id = creatId();
	function getOneKey(){
		var num = parseInt( Math.random()*10);
		return num.toString(10);
	}
	function creatId(){
		var idd = '';
		for(var i=0;i<18;i++){
			var k = getOneKey();
			if(k=='0')k='1';
			idd+=k;
		}
		return idd;
	}
    var sql = `INSERT INTO \`order\` `;
	var orderObj = {id:cre_id,user_id:queryData.user_id,state:0};//待确认状态

	sql = supeInsert(sql,orderObj);
	console.log(sql);
	connectMysql(sql, [''], (results) => {
        doNext();
    });
	function doNext(){
		//var upobj = {id:queryData.chopcarts_id};
		var upsql = `UPDATE shopcarts SET iswhere = 'order',order_id='${cre_id}' where id in (`;
		var len = queryData.shopcarts_id.length;
		for(var i=0;i<len;i++){
			var item = queryData.shopcarts_id[i];
			if(i!=len-1)upsql+=`'${item}',`;
			if(i==len-1)upsql+=`'${item}')`;
		}
		connectMysql(upsql, [''], (results) => {
			res.json(pushOk({order_id:cre_id}));
			res.end();
		});
    }
})

//修改订单状态
router.route('/vuedemo/update_order_state').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['order_id','state'];
	if(lostKeyStop(res,mustKey,queryData))return;
	var upsql = `UPDATE \`order\` SET state = '${queryData.state}' where id ='${queryData.order_id}'`;
		connectMysql(upsql, [''], (results) => {
			res.json(pushOk([]));
			res.end();
		});
})



var multer = require('multer')
//uuid工具可以生成唯一标示 需要安装


//设置保存规则
var storage = multer.diskStorage({
    //destination：字段设置上传路径，可以为函数
    destination: path.resolve(__dirname, '../public/headpics'),

    //filename：设置文件保存的文件名
    filename: function(req, file, cb) {

        let extName = file.originalname.slice(file.originalname.lastIndexOf('.'))
        let fileName = creatIdX();
        cb(null, fileName + extName)
    }
})

//设置过滤规则（可选）
var imageFilter = function(req, file, cb){
    var acceptableMime = ['image/jpeg', 'image/png', 'image/jpg', 'image/gif']
    //微信公众号只接收上述四种类型的图片
   // if(acceptableMime.indexOf(file.mimetype) !== -1){
        cb(null, true)
   // }else{
    //    cb(null, false)
   // }
}


function getOneKeyX(){
	var num = parseInt( Math.random()*36);
	return num.toString(36);
}
function creatIdX(){
	var idd = '';
	for(var i=0;i<8;i++){
		var k = getOneKeyX();
		if(k=='0')k='1';
		idd+=k;
	}
	return idd;
}
//设置限制（可选）
var imageLimit = {
    fieldSize: '4MB'
}

//创建 multer 实例
var imageUploader = multer({ 
    storage: storage,
    fileFilter: imageFilter,
    limits: imageLimit
}).array('photos', 12)    //定义表单字段、数量限制
router.route('/vuedemo/upimage').post(imageUploader, function(req, res, next) {
	
    console.log(req.files);
	 console.log(req.files[0].filename);
	res.json(pushOk({imgfile:'http://106.12.85.17:8090/public/headpics/'+req.files[0].filename}));
	console.log(2);
	res.end();
})
/*

var upsql = `UPDATE user SET iswhere = 'order',order_id='${cre_id}',takeover_addr ='${queryData.takeover_addr}'  where id in (`;
		var len = queryData.shopcarts_id.length;
		for(var i=0;i<len;i++){
			var item = queryData.shopcarts_id[i];
			if(i!=len-1)upsql+=`'${item}',`;
			if(i==len-1)upsql+=`'${item}')`;
		}

*/
//获取该用户所有订单
router.route('/vuedemo/get_order').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['user_id'];
	if(lostKeyStop(res,mustKey,queryData))return;
	
	var sql ='select * from `order` ';
	sql = supeSelect(sql,queryData);
	console.log(sql)
		connectMysql(sql, [''], (results) => {
			res.json(pushOk(results));
			res.end();
		});
})

//获取订单内所有商品
router.route('/vuedemo/get_goods_inorder').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['order_id'];
	if(lostKeyStop(res,mustKey,queryData))return;
	
	var sql = `	SELECT
				c.id as id , g.id as goods_id , g.name as goods_name ,s.name as shop_name, g.img_cover , g.money_now , g.money_old , g.hot_keyword , g.shop_id ,c.num ,c.user_id , c.norm ,c.updatetime,c.ischeck
				FROM
				shopcarts AS c
				LEFT JOIN goods_all AS g ON g.id = c.goods_id
				LEFT JOIN jd_shops AS s ON s.id = g.shop_id
				
				WHERE
				order_id = ${queryData.order_id} 
				
				`
	
	connectMysql(sql, [''], (results) => {
		res.json(pushOk(results));
		res.end();
	});
})

//取消订单
router.route('/vuedemo/cancel_order').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['order_id'];
	//DELETE FROM hy WHERE phone=?
	if(lostKeyStop(res,mustKey,queryData))return;
	var upsql = `UPDATE shopcarts SET iswhere = 'shopcar',order_id=null where order_id ='${queryData.order_id}' and (state=1 or state= )`;
	connectMysql(upsql, [''], (results) => {
		var desql = `DELETE FROM \`order\` where id ='${queryData.order_id}' and state=1`;
		connectMysql(desql, [''], (results) => {
			res.json(pushOk([]));
			res.end();
		});
		
	});
})

//删除订单
router.route('/vuedemo/delete_order').post(function (req, res, next) {
    var queryData = req.body;
	var mustKey = ['order_id'];
	//DELETE FROM hy WHERE phone=?
	if(lostKeyStop(res,mustKey,queryData))return;
	connectMysql(`select * from \`order\` where id= '${queryData.order_id}'`, [''], (result) => {
			if(result.length<0){
				res.json(pushError('订单异常,未找到该订单'));
				res.end();
			}else{
				if(result[0].state==1 ||result[0].state==0){
					res.json(pushError('订单未完成交易，请先支付，或取消支付'));
					res.end();
				}else{
					var desql1 = `DELETE FROM \`order\` where id ='${queryData.order_id}'`;
					var desql2 = `DELETE FROM \`shopcarts\` where order_id ='${queryData.order_id}'`;
					connectMysql(desql1, [''], (results) => {
						connectMysql(desql2, [''], (results) => {
							res.json(pushOk([]));
							res.end();
						});
					});
				}
			}
		});
})


//获取所有国际电话区号
router.route('/vuedemo/get_mobile_prefix').get(function (req, res, next) {
    var queryData = req.query;

	connectMysql(`select * from phone_area_code `, [''], (result) => {
			
				res.json(pushOk(result));
				res.end();
					
		
		});
})

//获取所有省
router.route('/vuedemo/get_provinces').get(function (req, res, next) {
    var queryData = req.query;

	connectMysql(`select * from provinces `, [''], (result) => {
			
				res.json(pushOk(result));
				res.end();
					
		
		});
})




//获取所有市
router.route('/vuedemo/get_cities').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['provinceid'];
	if(lostKeyStop(res,mustKey,queryData))return;
	var sql ='select * from cities';
	sql = supeSelect(sql,queryData);
	connectMysql(sql, [''], (result) => {
			
				res.json(pushOk(result));
				res.end();
					
		
		});
})

//获取所有区县
router.route('/vuedemo/get_areas').get(function (req, res, next) {
    var queryData = req.query;
	var mustKey = ['cityid'];
	if(lostKeyStop(res,mustKey,queryData))return;
	var sql ='select * from areas';
	sql = supeSelect(sql,queryData);
	connectMysql(sql, [''], (result) => {
			res.json(pushOk(result));
			res.end();
		});
})

//返回一个手机验证码
/*router.route('/vuedemo/phone_code').post(function (req, res, next) {
	var queryData = req.body;
    var mustKey = ['telphone'];
    if (lostKeyStop(res, mustKey, queryData)) return;
	connectMysql(`select phone from phone_code where \`phone\`='${queryData.telphone}' `, [''], (results) => {
		if (results.length > 0) {
			res.json(pushError('手机号已被注册'));
			res.end();
        } else {
			let code = parseInt(Math.random()*(9999-1000)+1000);
			let obj={}
			obj.phone = queryData.telphone;
			obj.code = code;
			var sql2 =  supeInsert(`INSERT INTO phone_code `,obj);
			connectMysql(sql2, [''], (results) => {
				console.log(results);
				res.json(code)
				res.end();
			});
		}
    });
})*/


router.get("/vuedemo/get_code_img", function (req, res, next) {

	var queryData = req.query;
    var mustKey = ['telphone'];
    if (lostKeyStop(res, mustKey, queryData)) return;
	var captcha = svgCaptcha.create({
				inverse: false, // 翻转颜色    
				fontSize: 48, // 字体大小    
				noise: 2, // 噪声线条数    
				width: 100, // 宽度    
				height: 40, // 高度    
				size: 4,// 验证码长度    
				ignoreChars: '0o1i', // 验证码字符中排除 0o1i  
			});  
		  
			res.json({img:String(captcha.data),str:captcha.text.toLowerCase(),'code':200,msg:'获取验证码成功'});
			res.end();
	/*if(queryData.ishave==1){
		connectMysql(`select * from user where \`tel\`='${queryData.telphone}' `, [''], (results) => {
			if (results.length > 0) {
				res.json(pushError('手机号已被注册'));
				res.end();
			} else {
				var captcha = svgCaptcha.create({
					inverse: false, // 翻转颜色    
					fontSize: 48, // 字体大小    
					noise: 2, // 噪声线条数    
					width: 100, // 宽度    
					height: 40, // 高度    
					size: 4,// 验证码长度    
					ignoreChars: '0o1i', // 验证码字符中排除 0o1i  
				});  
			  
				res.json({img:String(captcha.data),str:captcha.text.toLowerCase(),'code':200,msg:'获取验证码成功'});
				res.end();
			}
		});
	}else{
		var captcha = svgCaptcha.create({
				inverse: false, // 翻转颜色    
				fontSize: 48, // 字体大小    
				noise: 2, // 噪声线条数    
				width: 100, // 宽度    
				height: 40, // 高度    
				size: 4,// 验证码长度    
				ignoreChars: '0o1i', // 验证码字符中排除 0o1i  
			});  
		  
			res.json({img:String(captcha.data),str:captcha.text.toLowerCase(),'code':200,msg:'获取验证码成功'});
			res.end();
	}
	
	*/
    
});




//router.get('/vuedemo/getOneClassify', function (req, res, next) {
//    connectMysql("select * from oneclassification", '', (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getShowIndex/:name', function (req, res, next) {
//    console.log(req.params.name)
//    console.log(req.session.phone);
//    connectMysql("select * from showindex where sName = ?", [req.params.name], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/yldata', function (req, res, next) {
//    connectMysql("SELECT * FROM yltj", '', (results) => {
//        let yj = results;
//        connectMysql("SELECT * FROM ylwj", '', (results) => {
//            let ylwj = results;
//            connectMysql("SELECT * FROM ylfx", '', (results) => {
//                let ylfx = results;
//                res.json({ 'yj': yj, 'ylwj': ylwj, 'ylfx': ylfx });
//            })
//        })
//    })
//})
//router.get("/image", function (req, res, next) {
//    var captcha = svgCaptcha.create({
//        inverse: false, // 翻转颜色
//        fontSize: 48, // 字体大小
//        noise: 2, // 噪声线条数
//        width: 100, // 宽度
//        height: 40, // 高度
//        size: 4,// 验证码长度
//        ignoreChars: '0o1i', // 验证码字符中排除 0o1i
//    });  // 保存到session,忽略大小写
//    req.session.code = captcha.text.toLowerCase();// 生成验证码 存进session
//    console.log(captcha.text.toLowerCase());
//    //保存到cookie 方便前端调用验证  //
//    //res.cookie('captcha', req.session);
//    res.setHeader('Content-Type', 'image/html');
//    res.write(String(captcha.data));
//    res.end();
//});
//router.get('/vuedemo/ft', function (req, res, next) {
//    connectMysql("select * from start", '', (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/ftlm/:sid', function (req, res, next) {
//    connectMysql("SELECT * FROM start WHERE sid = ?", [req.params.sid], (results) => {
//        res.json(results[0]);
//    })
//})
//router.get('/vuedemo/myfw', function (req, res, next) {
//    connectMysql("SELECT * FROM grzx WHERE gstate = 1", '', (results) => {
//        let mc = results;
//        connectMysql("SELECT * FROM grzx WHERE gstate = 0", '', (results) => {
//            let xs = results;
//            connectMysql("SELECT * FROM hy WHERE phone = ?", [global.phone], (results) => {
//                let hy = results;
//                res.json({ 'mc': mc, 'xs': xs, 'hy': hy });
//            })
//        })
//    })
//})
//router.get('/vuedemo/xx', function (req, res, next) {
//    connectMysql("SELECT * FROM user WHERE phone = ?", [req.session.phone], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/sjh', function (req, res, next) {
//    if (req.session.phone) {
//        connectMysql("SELECT * FROM user WHERE phone = ?", [req.session.phone], (results) => {
//            let phoneName = results[0].phoneName;
//            connectMysql("SELECT * FROM hy WHERE phone = ?", [req.session.phone], (results) => {
//                res.json({
//                    'sjh': req.session.phone,
//                    'phoneName': phoneName,
//                    'hyzt': results[0],
//                });
//            })
//        })
//    } else {
//        console.log('请登录');
//    }
//})
//router.get('/vuedemo/gqla', function (req, res, next) {
//    connectMysql("DELETE FROM hy WHERE phone=?", [req.session.phone], (results) => {
//        console.log(results, 238);
//    })
//})
//router.get('/logout', function (req, res, next) {
//    delete req.session.phone;
//    res.redirect('/login');
//})
//router.get('/vuedemo/ckkk', function (req, res, next) {
//    connectMysql("SELECT s.sImg,s.sVideoname,s.vid,l.sj FROM lsjl AS l LEFT JOIN showindex AS s ON l.vid = s.vid WHERE phone = ?", [req.session.phone], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/sca/:vid', function (req, res, next) {
//    connectMysql("DELETE FROM lsjl WHERE phone = ? AND vid = ?", [req.session.phone, req.params.vid], (results) => {
//    })
//})
//router.get('/vuedemo/detailsData/:vid', function (req, res, next) {
//    connectMysql("select * from allvideo where vid = ?", [req.params.vid], (results) => {
//        let details = results[0];
//        if (req.session.phone) {
//            var sj = new Date().getTime();
//            connectMysql("SELECT * FROM lsjl WHERE phone = ? AND vid = ?", [req.session.phone, req.params.vid], (results) => {
//                console.log(results, 187);
//                if (results[0]) {
//                    connectMysql("UPDATE lsjl SET sj = ? WHERE phone = ? AND vid = ?", [sj, req.session.phone, req.params.vid], (results) => {
//                        console.log(results, 190);
//                    })
//                } else {
//                    connectMysql("INSERT INTO lsjl values(0,?,?,?)", [req.session.phone, req.params.vid, sj], (results) => {
//                        console.log(results, 194);
//                    })
//                }
//            })
//        }
//        connectMysql("select * from episode where vid = ? and category = ?", [req.params.vid, '正片'], (results) => {
//            let zhengpian = results;
//            connectMysql("select * from episode where vid = ? and category = ?", [req.params.vid, '花絮'], (results) => {
//                let huaxu = results;
//                connectMysql("select * from episode where vid = ? and category = ?", [req.params.vid, '精华'], (results) => {
//                    let jinghua = results;
//                    connectMysql("select * from showindex where sName = ? order by rand() limit 5", [details.oName], (results) => {
//                        let xg = results;
//                        res.json({
//                            'details': details,
//                            'zhengpian': zhengpian,
//                            'huaxu': huaxu,
//                            'jinghua': jinghua,
//                            'xg': xg
//                        })
//                    })
//                })
//            })
//        })
//    })
//})
//router.get('/vuedemo/iscollect/:vid/:is', function (req, res, next) {
//    switch (req.params.is) {
//        case '0':
//            connectMysql("delete from collect where vid = ? and userName = ?", [req.params.vid, req.session.phone], (results) => {
//            })
//            break;
//        case '1':
//            connectMysql("insert into collect values (null,?,?)", [req.params.vid, req.session.phone], (results) => {
//            })
//            break;
//        case '2':
//            connectMysql("select * from collect where vid = ? and userName = ?", [req.params.vid, req.session.phone], (results) => {
//                if (results[0]) {
//                    res.json(true);
//                } else {
//                    res.json(false);
//                }
//            })
//            break;
//        case '3':
//            connectMysql("select * from showindex where vid in (select vid from collect where userName = ?)", [req.session.phone], (results) => {
//                res.json(results);
//            })
//            break;
//    }
//})
//router.get('/vuedemo/getss', function (req, res, next) {
//    connectMysql("SELECT * FROM oneclassification LIMIT 0,6", '', (results) => {
//        let tja = results;
//        connectMysql("SELECT * FROM showindex", '', (results) => {
//            let flList = results;
//            res.json({
//                tja: tja,
//                flList: flList,
//            });
//        })
//    })
//})
//router.get('/vuedemo/select/:kw', function (req, res, next) {
//    console.log(req.params.kw);
//    connectMysql("SELECT list.sName,list.sVideoname,list.sImg,dish.vid,dish.oName,dish.vName,dish.vStation,dish.vCompere,dish.vGuests FROM allvideo AS dish LEFT JOIN showindex AS list ON list.vid = dish.vid WHERE dish.vName Like ?", ['%' + req.params.kw + '%'], (results) => {
//        console.log(results);
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getsjaa/:num', function (req, res, next) {
//    connectMysql("SELECT * FROM showindex WHERE sName = ? LIMIT 0,8", [req.params.num], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getProvinces', function (req, res, next) {
//    connectMysql("SELECT * FROM provinces", '', (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getCities/:index', function (req, res, next) {
//    connectMysql("SELECT c.city,p.provinceid,c.cityid FROM cities AS c LEFT JOIN provinces AS p ON p.provinceid = c.provinceid WHERE p.province = ?", [req.params.index], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getAreas/:index', function (req, res, next) {
//    connectMysql("SELECT a.areaid,a.area,c.cityid FROM areas AS a LEFT JOIN cities AS c ON c.cityid = a.cityid WHERE c.city = ?", [req.params.index], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/xgxx/:qb', function (req, res, next) {
//    var qb = JSON.parse(req.params.qb);
//    connectMysql("UPDATE user SET phoneName = ?,gsex = ?,gadress = ?,gsign = ? WHERE phone = ? AND uid = ?", [qb.name, qb.sex, qb.addr, qb.sign, req.session.phone, qb.uid], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/isjr/:sid/:is', function (req, res, next) {
//    switch (req.params.is) {
//        case 'out':
//            connectMysql("delete from ft where sid = ? and phone = ?", [req.params.sid, req.session.phone], (results) => {
//            })
//            break;
//        case 'join':
//            connectMysql("insert into ft values (null,?,?)", [req.session.phone, req.params.sid], (results) => {
//            })
//            break;
//        case 'get':
//            connectMysql("select * from ft where sid = ? and phone = ?", [req.params.sid, req.session.phone], (results) => {
//                console.log(results[0]);
//                if (results[0]) {
//                    var txt = true;
//                } else {
//                    var txt = false;
//                }
//                res.json(txt);
//            })
//            break;
//        case 'myjoin':
//            connectMysql("select * from start where sid in (select sid from ft where phone = ?)", [req.session.phone], (results) => {
//                res.json(results);
//            })
//            break;
//    }
//})
//router.get('/vuedemo/smallVideo/:is', function (req, res, next) {
//    switch (req.params.is) {
//        case 'insert':
//            connectMysql("insert into SmallVideoColl values(null,?,1)", [req.session.phone], (results) => {
//            })
//            break;
//        case 'delete':
//            connectMysql("delete from SmallVideoColl where username=? and videoId = 1", [req.session.phone], (results) => {
//            })
//            break;
//        case 'select':
//            connectMysql("select* from SmallVideoColl where username=? and videoId = 1", [req.session.phone], (results) => {
//                if (results[0]) {
//                    res.json(true);
//                } else {
//                    res.json(false);
//                }
//            })
//            break;
//    }
//})
//router.get('/vuedemo/getfenlei/:name', function (req, res, next) {
//    connectMysql("select t.tName,t.tStation from twoclassification t where t.oName = ?", [req.params.name], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/getfenleidata/:name/:type/:station', function (req, res, next) {
//    console.log(req.params);
//    if (req.params.type != '全部' && req.params.station != '全部') {
//        connectMysql("SELECT s.sImg,s.sVideoname,s.stxt,a.vid FROM showindex s LEFT JOIN allvideo a ON a.vid = s.vid WHERE a.oName = ? AND a.classify = ? AND a.vStation LIKE ? ORDER BY a.VPlay DESC", [req.params.name, req.params.type, '%' + req.params.station + '%'], (results) => {
//            res.json(results);
//        })
//    } else {
//        if (req.params.type != '全部') {
//            connectMysql("SELECT s.sImg,s.sVideoname,s.stxt,a.vid FROM showindex s LEFT JOIN allvideo a ON a.vid = s.vid WHERE a.oName = ? AND a.classify = ? ORDER BY a.VPlay DESC", [req.params.name, req.params.type], (results) => {
//                res.json(results);
//            })
//        } else if (req.params.station != '全部') {
//            connectMysql("SELECT s.sImg,s.sVideoname,s.stxt,a.vid FROM showindex s LEFT JOIN allvideo a ON a.vid = s.vid WHERE a.oName = ? AND a.vStation LIKE ? ORDER BY a.VPlay DESC", [req.params.name, '%' + req.params.station + '%'], (results) => {
//                res.json(results);
//            })
//        } else {
//            connectMysql("SELECT s.sImg,s.sVideoname,s.stxt,a.vid FROM showindex s LEFT JOIN allvideo a ON a.vid = s.vid WHERE a.oName = ? ORDER BY a.VPlay DESC", [req.params.name], (results) => {
//                res.json(results);
//            })
//        }
//    }
//})
//router.get('/vuedemo/hya/:dq', function (req, res, next) {
//    var dqsj = JSON.parse(req.params.dq);
//    console.log(req.params.dq);
//    connectMysql("INSERT INTO hy VALUES (null,?,?,1)", [req.session.phone, dqsj], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/hyxga/:dq', function (req, res, next) {
//    var dqsj = JSON.parse(req.params.dq);
//    console.log(req.params.dq);
//    connectMysql("UPDATE hy SET dqsj= ? WHERE phone = ? AND state = 1", [dqsj, req.session.phone], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/gd1', function (req, res, next) {
//    connectMysql("SELECT * FROM grzx WHERE gstate = 1", [], (results) => {
//        res.json(results);
//    })
//})
//router.get('/vuedemo/gd2', function (req, res, next) {
//    connectMysql("SELECT * FROM grzx WHERE gstate = 0", [], (results) => {
//        console.log(results, 395);
//        res.json(results);
//    })
//})
//router.get('/vuedemo/gd3/:gstate/:gid', function (req, res, next) {
//    connectMysql("UPDATE grzx SET gstate = ? WHERE gid = ?", [req.params.gstate, req.params.gid], (results) => {
//        console.log(results, 396);
//        res.json(results);
//    })
//})
//router.get('/vuedemo/hy/:a/:b', function (req, res, next) {
//    connectMysql("select * from showindex WHERE sName = ? AND sSetnumber = ?", [req.params.a, req.params.b], (results) => {
//        res.json(results);
//    })
//})
module.exports = router;